package com.example.myapplication;

import android.os.Looper;

import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.connectTimeout(15, TimeUnit.SECONDS);
        client = builder.build();
    }

    public static JsonObject buildJSON(String[] keys, Object... values) {
        JsonObject jsonObject =null;
        try {
            jsonObject = new JsonObject();
            for (int i = 0; i < keys.length; ++i) {
                jsonObject.put(keys[i], values[i]);
            }
        } catch (Exception e) {
            jsonObject = null;
        }
        return jsonObject;
        }
    public static RequestBody buildBody(JsonObject json) {
        return RequestBody.create(MediaType.parse("application/json; charset =utf-8"), json.toString());
    }
    public static String host = "http://121.9.253.237:8888/traffic/api/v2/";
    public static Request buildRequest(String api, RequestBody body) {
        return new Request.Builder().url(host + api).post(body).build();
    }
    public static Call buildCall(Request request) {
        return client.newCall(request);
    }
    public static Handler handler = new Handler(Looper.getMainLooper());
    public interface AsyncCallBack {
        void onFailure(Exception e);
        void onResponse(String json);
    }
    public static void asyncRequest( final AsyncCallBack callBack,String api,String[] keys, Object...values){
        JsonObject jsonObject= buildJSON(keys, values);
        RequestBody requestBody=buildBody(jsonObject);
        Request request = buildRequest(api, requestBody);
        Call call=buildCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onResponse(json);
                    }
                });
                }
        });
    }
    }

